﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 残影效果
/// </summary>
public class GhostShadow : MonoBehaviour {
    public float Duration = 1;
    public float Interval = 0.5f;
    public Color GhostShadowColor=new Color(1,1,1);

    public bool enable = true;

    private float nextTime;
    private SpriteRenderer sr;
    private void Start()
    {
        sr = GetComponent<SpriteRenderer>();
    }
    private void Update()
    {
        if (Time.time < nextTime || !enable || !sr)
        {
            return;
        }
        nextTime = Time.time + Interval;
        GameObject go = ObjectPool.Instance.GetEmptyGO("GhostShadow"+gameObject.name);
        if (go.GetComponent<SpriteRenderer>())
        {
            SpriteRenderer _sr = go.GetComponent<SpriteRenderer>();
            _sr.sprite = sr.sprite;
            _sr.material = sr.material;
            _sr.sortingOrder = sr.sortingOrder-1;
        }
        else
        {
            SpriteRenderer _sr = go.AddComponent<SpriteRenderer>();
            _sr.sprite = sr.sprite;
            _sr.material = sr.material;
            _sr.sortingOrder = sr.sortingOrder-1;
        }
        go.transform.position = transform.position;
        go.transform.rotation = transform.rotation;
        go.transform.localScale = transform.localScale;
        if (go.GetComponent<ShadowDuration>())
        {
            go.GetComponent<ShadowDuration>().SetShadow(Duration, GhostShadowColor);
        }
        else
        {
            go.AddComponent<ShadowDuration>().SetShadow(Duration, GhostShadowColor);
        }
    }

}
public class ShadowDuration : MonoBehaviour
{
    float duration=-1;
    float dieTime=0;
    Color startColor;
    /// <summary>
    /// 设置残影的持续时间和开始颜色
    /// </summary>
    /// <param name="d"></param>
    /// <param name="_startColor"></param>
    public void SetShadow(float d,Color _startColor)
    {
        duration = d;
        dieTime = Time.time + d;
        StartCoroutine(Timer(d));
        startColor = _startColor;
    }
    private void OnEnable()
    {
        if (duration > 0)
        {
            StartCoroutine(Timer(duration));
        }
        GetComponent<SpriteRenderer>().color = startColor;
    }
    private void Update()
    {
        if (dieTime <= 0)
        {
            return;
        }
        GetComponent<SpriteRenderer>().color =
            new Color(
                startColor.r,
                startColor.g,
                startColor.b,
                startColor.a*((dieTime-Time.time)/duration)
                );
    }
    private IEnumerator Timer(float t)
    {
        yield return new WaitForSeconds(t);
        DestroyThis();
    }

    private void DestroyThis()
    {
        ObjectPool.Instance.InPool(gameObject);
    }
}